package com.example.manager.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.manager.common.QueryPageParam;
import com.example.manager.common.Result;
import com.example.manager.entity.Employees;
import com.example.manager.entity.Employeestatus;
import com.example.manager.mapper.EmployeesMapper;
import com.example.manager.service.EmployeesService;
import com.example.manager.service.EmployeestatusService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;

import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.core.io.InputStreamResource;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.MediaType;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fwy
 * @since 2024-07-18
 */
@RestController
@RequestMapping("/employees")
public class EmployeesController {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private EmployeesService employeesService;

    @GetMapping("/list")
    public List<Employees> list(){
        return employeesService.list();
    }
    //查询（模糊，匹配）
    @PostMapping("/listP")
    public List<Employees> listP(@RequestBody Employees employees){
        LambdaQueryWrapper<Employees> lambdaQueryWrapper=new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(employees.getName())){
            lambdaQueryWrapper.like(Employees::getName,employees.getName());
        }return employeesService.list(lambdaQueryWrapper);
    }


@PostMapping("/listPage")
    public List<Employees> listPage(@RequestBody QueryPageParam query){
       System.out.println(query);
   HashMap param=query.getParam();
   String name=(String)param.get("name");

   Page<Employees> page=new Page<>();
   page.setCurrent(query.getPageNum());
   page.setSize(query.getPageSize());

   LambdaQueryWrapper<Employees> lambdaQueryWrapper=new LambdaQueryWrapper<>();
   lambdaQueryWrapper.like(Employees::getName,name);

  //  IPage result=employeesService.pageC(page);
   IPage result=employeesService.pageCC(page,lambdaQueryWrapper);

    return result.getRecords();
    }

    @PostMapping("/listPage1")
    public Result listPage1(@RequestBody QueryPageParam query){
       System.out.println(query);
        HashMap param=query.getParam();
        String employeeID =(String)param.get("employeeID");

        Page<Employees> page=new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Employees> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(employeeID)) {
            lambdaQueryWrapper.eq(Employees::getEmployeeID, employeeID); // 确保使用了正确的字段名称
        }


        // 根据 gender 查询
        String gender = (String) query.getParam().get("gender");
        if (StringUtils.isNotBlank(gender)) {
            lambdaQueryWrapper.eq(Employees::getGender, gender);
        }

        // 根据 jobSeries 查询
        String jobSeries = (String) query.getParam().get("jobSeries");
        if (StringUtils.isNotBlank(jobSeries)) {
            lambdaQueryWrapper.eq(Employees::getJobSeries, jobSeries);
        }

        // 根据 position 查询
        String position = (String) query.getParam().get("position");
        if (StringUtils.isNotBlank(position)) {
            lambdaQueryWrapper.eq(Employees::getPosition, position);
        }

        // 根据 workLocation 查询
        String workLocation = (String) query.getParam().get("workLocation");
        if (StringUtils.isNotBlank(workLocation)) {
            lambdaQueryWrapper.eq(Employees::getWorkLocation, workLocation);
        }

        // 根据 department 查询
        String department = (String) query.getParam().get("department");
        if (StringUtils.isNotBlank(department)) {
            lambdaQueryWrapper.eq(Employees::getDepartment, department);
        }
        // IPage result=employeesService.pageC(page);
        IPage result=employeesService.pageCC(page,lambdaQueryWrapper);

        return Result.suc(result.getRecords(),result.getTotal());
    }

    private String convertDateString(String originalDate) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date date = inputFormat.parse(originalDate);
            return outputFormat.format(date);
        } catch (ParseException e) {
            // 在实际应用中，您可能需要记录这个异常或进行适当的错误处理
            e.printStackTrace();
            return null;
        }
    }
    @Autowired
    private EmployeestatusService employeestatusService;
@Autowired
    private EmployeesMapper employeesMapper;
    @Transactional(rollbackFor = Exception.class) // 确保事务性
    @PostMapping("/save")
    public Result save(@RequestBody Employees employees) throws ParseException {

        String originalDateOfBirth = String.valueOf(employees.getDateOfBirth());
        String originalHireDate = String.valueOf(employees.getHireDate());

        // 使用上面定义的方法转换日期格式
        String newDateOfBirth = convertDateString(originalDateOfBirth);

        System.out.println(employees);
        try {
            String hireDate = convertDateString(originalHireDate);
                if ("实习生".equals(employees.getEmployeeType())) {
                    String internshipEndDate = calculateInternshipEndDate(hireDate);
                    employees.setInternship(hireDate + "~" + internshipEndDate);
                } else if ("正社员".equals(employees.getEmployeeType()) || "派遣社员".equals(employees.getEmployeeType())) {
                    String probationEndDate = calculateProbationEndDate(hireDate);
                    employees.setProbation(hireDate + "~" + probationEndDate);
                }
        } catch (ParseException e) {
            return Result.fail();
        }

        // 插入 Employees 记录，MyBatis-Plus 会自动处理自增ID
        boolean success = employeesService.save(employees);
        if (!success) {
            return Result.fail();
        }

        // 此时 employees 对象中已经包含了自增的 EmployeeID
        Integer newEmployeeId = employees.getEmployeeID();
        System.out.println("新生成的 EmployeeID: " + newEmployeeId);

        // 使用新生成的 EmployeeID 创建 Employeestatus 记录
        Employeestatus employeestatus = new Employeestatus();
        employeestatus.setId(newEmployeeId);
        employeestatus.setWorkLocation(employees.getWorkLocation());
        // ... 设置其他字段 ...
        employeestatus.setDepartment(employees.getDepartment());
        employeestatus.setJobLevel(employees.getJobLevel());
       // employeestatus.setPosition(employees.getPosition());
        employeestatus.setJoiningDate(employees.getHireDate());
        employeestatus.setName(employees.getName());

        // 保存 Employeestatus 记录
        success = employeestatusService.save(employeestatus);
        if (!success) {
            return Result.fail();
        }

        return Result.suc("员工信息和状态保存成功");
    }


        private String calculateInternshipEndDate(String hireDate) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date startDate = sdf.parse(hireDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
           // calendar.add(Calendar.YEAR, 1); // 增加一年
            calendar.set(Calendar.MONTH, 6); // 设置月份为7月
            calendar.set(Calendar.DAY_OF_MONTH, 31); // 设置天数为31
            return sdf.format(calendar.getTime());
        }

        private String calculateProbationEndDate(String hireDate) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date startDate = sdf.parse(hireDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            calendar.add(Calendar.MONTH, 6); // 增加6个月
            return sdf.format(calendar.getTime());
        }
       // return employeesService.save(employees)?Result.suc():Result.fail();


    @DeleteMapping("/del")
    public Result delete(@RequestParam String employeeId) {
        return  employeesService.removeById(employeeId) ? Result.suc() : Result.fail();
    }


    @PostMapping("/update")
    public Result update(@RequestBody Employees employees) {
        // 更新 Employees 表
        boolean isEmployeesUpdated = employeesService.updateById(employees);

        if (isEmployeesUpdated) {
            // 如果 Employees 表更新成功，接着更新 Employeestatus 表
            Employeestatus employeestatus = new Employeestatus();
            employeestatus.setId(employees.getEmployeeID());
            employeestatus.setWorkLocation(employees.getWorkLocation());
            employeestatus.setDepartment(employees.getDepartment());
            employeestatus.setJobLevel(employees.getJobLevel());
            employeestatus.setJoiningDate(employees.getHireDate());
            employeestatus.setName(employees.getName());

            boolean isEmployeestatusUpdated = employeestatusService.updateById(employeestatus);
            return isEmployeestatusUpdated ? Result.suc() : Result.fail();
        } else {
            return Result.fail();
        }
    }

    @PostMapping("/download")
    public ResponseEntity<InputStreamResource> downloadEmployees(@RequestBody List<Employees> employees) {
        XSSFWorkbook workbook = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("员工信息");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            int col = 0;
            String[] headers = {"员工号", "所属公司", "社员区分", "员工姓名", "性别", "籍贯", "毕业学校", "专业", "学历", "生日", "职系", "职级", "职位", "工作地点", "所属部门", "业务负责人", "教育负责人", "入职日", "实习期间", "试用期间"};
            for (String header : headers) {
                headerRow.createCell(col++).setCellValue(header);
            }

            // 填充数据行
            for (Employees employee : employees) {
                Row row = sheet.createRow(employees.indexOf(employee) + 1);
                col = 0;
                row.createCell(col++).setCellValue(employee.getEmployeeID());
                row.createCell(col++).setCellValue(employee.getCompanyName());
                row.createCell(col++).setCellValue(employee.getEmployeeType());
                row.createCell(col++).setCellValue(employee.getName());
                row.createCell(col++).setCellValue(employee.getGender());
                row.createCell(col++).setCellValue(employee.getOrigin());
                row.createCell(col++).setCellValue(employee.getSchool());
                row.createCell(col++).setCellValue(employee.getMajor());
                row.createCell(col++).setCellValue(employee.getEducationLevel());
                row.createCell(col++).setCellValue(dateFormat.format(employee.getDateOfBirth())); // 格式化出生日期


                row.createCell(col++).setCellValue(employee.getJobSeries());
                row.createCell(col++).setCellValue(String.valueOf(employee.getJobLevel()));
                row.createCell(col++).setCellValue(employee.getPosition());
                row.createCell(col++).setCellValue(employee.getWorkLocation());
                row.createCell(col++).setCellValue(employee.getDepartment());
                row.createCell(col++).setCellValue(employee.getBusinessManager());
                row.createCell(col++).setCellValue(employee.getEducationCheif());
                row.createCell(col++).setCellValue(dateFormat.format(employee.getHireDate())); // 格式化入职日期
                row.createCell(col++).setCellValue(employee.getInternship());
                row.createCell(col++).setCellValue(employee.getProbation());
            }

            // 将Workbook写入到ByteArrayOutputStream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            workbook.write(bos);

            // 构造HTTP响应头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Content-Disposition", "attachment; filename=员工信息.xlsx");
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 将数据转换为InputStreamResource
            InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(bos.toByteArray()));

            // 返回ResponseEntity
            return ResponseEntity.ok()
                    .headers(httpHeaders)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }

    @PostMapping("/upload")
    public ResponseEntity<Result> uploadEmployees(@RequestParam("file") MultipartFile file) {
        System.out.println(file);
        if (!file.isEmpty()) {
            System.out.println("!11");
            try {
                Workbook workbook = WorkbookFactory.create(file.getInputStream());
                Sheet sheet = workbook.getSheetAt(0); // 假设只有一个工作表
                List<Employees> employeesToSave = new ArrayList<>();

                for (Row row : sheet) {
                    if (row.getRowNum() == 0) continue; // 跳过标题行

                    Employees employee = new Employees();
                    // 假设 Excel 列的顺序和 Employees 实体的字段顺序一致
                    employee.setCompanyName(row.getCell(0).getStringCellValue());
                    System.out.println(row.getCell(1));
                    employee.setEmployeeType(row.getCell(1).getStringCellValue());
                    employee.setName(row.getCell(2).getStringCellValue());
                    employee.setGender(row.getCell(3).getStringCellValue());
                    employee.setOrigin(row.getCell(4).getStringCellValue());
                    employee.setSchool(row.getCell(5).getStringCellValue());
                    employee.setMajor(row.getCell(6).getStringCellValue());
                    employee.setEducationLevel(row.getCell(7).getStringCellValue());
                    employee.setJobSeries(row.getCell(9).getStringCellValue());
                    Cell dateOfBirthCell = row.getCell(8);
                    if (DateUtil.isCellDateFormatted(dateOfBirthCell)) {
                        // 如果单元格是日期格式，使用 Apache POI 的 DateUtil 转换
                        employee.setDateOfBirth(DateUtil.getJavaDate(dateOfBirthCell.getNumericCellValue()));
                    } else {
                        // 如果单元格不是日期格式，尝试将其作为文本解析
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
                        try {
                            Date date = dateFormat.parse(dateOfBirthCell.getStringCellValue());
                            employee.setDateOfBirth(date);
                        } catch (ParseException e) {
                            // 日期解析失败，处理错误或使用默认值
                            // 这里可以记录日志、设置默认日期或采取其他错误处理措施
                            System.err.println("日期解析失败，单元格值：" + dateOfBirthCell.getStringCellValue());
                            // 例如，设置默认日期
                            // employee.setDateOfBirth(new Date()); // 或者其他合适的默认日期
                        }}
                    employee.setDepartment(row.getCell(13).getStringCellValue());
                    employee.setPosition(row.getCell(11).getStringCellValue());
                    employee.setWorkLocation(row.getCell(12).getStringCellValue());
                    employee.setBusinessManager(row.getCell(14).getStringCellValue());
                    employee.setEducationCheif(row.getCell(15).getStringCellValue());
                    // 处理职级字段
                    employee.setJobLevel(Integer.valueOf(row.getCell(10).getStringCellValue()));
                    Cell hireDateCell = row.getCell(16); // 获取入职日期单元格
                    if (hireDateCell != null) {
                        // 检查单元格是否为字符串类型
                        if (hireDateCell.getCellType() == Cell.CELL_TYPE_STRING) {
                            // 如果单元格是字符串类型的日期，尝试转换为java.util.Date
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 根据实际日期格式创建SimpleDateFormat对象
                            String hireDateString = hireDateCell.getStringCellValue();
                            try {
                                Date hireDate = sdf.parse(hireDateString);
                                employee.setHireDate(hireDate); // 使用正确的setter方法
                            } catch (ParseException e) {
                                // 处理日期解析异常
                                // 这里可以记录日志或返回错误信息
                                e.printStackTrace();
                            }
                        } else if (hireDateCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                            // 如果单元格是数字类型，转换为java.util.Date
                            Date hireDate = DateUtil.getJavaDate(hireDateCell.getNumericCellValue());
                            employee.setHireDate(hireDate);
                        } else {
                            // 如果单元格类型既不是字符串也不是数字，处理其他情况
                            // 例如，可以设置默认值或记录警告
                        }
                    }
                    employee.setInternship(row.getCell(17).getStringCellValue());
                    XSSFCell cell = (XSSFCell) row.getCell(18); // 获取第18列的单元格
                    if (cell == null) {
                        // 单元格不存在，根据业务逻辑处理，例如使用null或空字符串
                        System.err.println("在第 " + row.getRowNum() + " 行的第18列单元格不存在，将使用默认值或null。");
                        employee.setProbation(null); // 或者使用合适的默认值，例如 ""
                    } else {
                        // 获取单元格的文本值，可以为空字符串
                        String probationValue = cell.getStringCellValue();
                        employee.setProbation(probationValue); // 可能为空字符串
                    }
                    employeesToSave.add(employee);
                }

                boolean isSaved = employeesService.saveBatch(employeesToSave);
                return isSaved
                        ? ResponseEntity.ok(Result.suc("上传成功，共导入 " + employeesToSave.size() + " 条记录"))
                        : ResponseEntity.badRequest().body(Result.fail());
            } catch (IOException | ParseException e) {
                return ResponseEntity.internalServerError().body(Result.fail());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            System.out.println("没有扫描到文件");
            return ResponseEntity.badRequest().body(Result.fail());
        }
    }
    }


